/**
 * 
 */
package com.mvc.service.utils.impl;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.management.loading.PrivateMLet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.cloopen.rest.sdk.CCPRestSDK;
import com.mvc.dao.BaseDaoI;
import com.mvc.framework.constant.GlobalConstant;
import com.mvc.model.mb.archive.BaseInfo;
import com.mvc.model.mb.archive.ValidateInfo;
import com.mvc.service.utils.ValidateServiceI;
import com.mvc.utils.MD5Util;
import com.mvc.utils.SendEmail;
import com.mvc.utils.StringUtil;

/**
 * @author qingjie
 *
 */
@Service
public class ValidateServiceImpl implements ValidateServiceI {
	
	@Autowired
	private BaseDaoI<ValidateInfo> vbdi;
	@Autowired
	private BaseDaoI<BaseInfo> bbdi;

	@Override
	public String getPhoneValidateCode(String phone,HttpSession session) {
		//如果存在手机验证码session，则进行销毁
		if(session.getAttribute(GlobalConstant.SESSION_PHONE)!=null){
			//移除session
			session.removeAttribute(GlobalConstant.SESSION_PHONE);
		}
		//获取验证码
		String validateCode = StringUtil.getRandom();
		//把验证码和电话号码通过加密后，形成token,并且存入session 
		session.setAttribute(GlobalConstant.SESSION_PHONE, MD5Util.md5(validateCode+","+phone));
		//设置session时间为2分钟
		session.setMaxInactiveInterval(2*60);
		return validateCode;
	}

	@Override
	public boolean sendTemplateSms(Map<String, Object> map) {
		String accountSid = "8a48b5515249574b015252af55751033";
		String accountToken = "ed8667cafc7a46649781225d8a36b823";
		String appId = "8a48b5515249574b015252c3cbf31091";
		boolean b = false;
		HashMap<String, Object> result = null;
		CCPRestSDK restAPI = new CCPRestSDK();
		restAPI.init("app.cloopen.com", "8883");// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
		restAPI.setAccount(accountSid, accountToken);// 初始化主帐号和主帐号TOKEN
		restAPI.setAppId(appId);// 初始化应用ID
		//("号码1,号码2等","模板Id" ,new String[]{"模板内容1","模板内容2"});
		result = restAPI.sendTemplateSMS((String)map.get("phoneNumber"),(String)map.get("templateId") ,new String[]{(String)map.get("content"),"2"});

		System.out.println("SDKTestSendTemplateSMS result=" + result);
		if("000000".equals(result.get("statusCode"))){
			//正常返回输出data包体信息（map）
			HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
			Set<String> keySet = data.keySet();
			for(String key:keySet){
				Object object = data.get(key);
				System.out.println(key +" = "+object);
			}
			b = true;
		}else{
			//异常返回输出错误码和错误信息
			System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
			b = false;
		}
		return b;
	}

	@Override
	public boolean sendTemplateEmail(Map<String, Object> map) {
		boolean b = false;
		StringBuffer sb = new StringBuffer("点击下面链接激活账号，有效期为48小时，否则重新注册账号，链接只能使用一次，请尽快激活！<br>");
		sb.append("http://localhost:8080/user/admin/emailRegister?email="); 
		sb.append(MD5Util.md5((String)map.get("email")));
		sb.append("&validateCode=");
		sb.append(MD5Util.md5((String)map.get("validateCode")));
		sb.append("&bid=");
		sb.append((String)map.get("bid"));
		sb.append("");
		try {
			//实现邮件发送
			SendEmail.send((String)map.get("email"), sb.toString());
			String tString = JSON.toJSONString(map);
			//数据转为实体类
			ValidateInfo vi = JSON.parseObject(tString, ValidateInfo.class);
			vi.setCreateDate(GlobalConstant.SDF.format(new Date()));
			//执行对临时表的保存
			vbdi.saveOrUpdate(vi);
			b = true;
		} catch (Exception e) {
			b = false;
			e.printStackTrace();
		}
		return b;
	}

	@Override
	public int validateEmailLink(ValidateInfo vi){
		int state = 0;//0：不存在该记录；1：验证超时，链接失效；2：验证码或邮箱错误；3：验证成功
		ValidateInfo vInfo = vbdi.get("from ValidateInfo v where v.bid = '"+vi.getBid()+"'");
		if(vInfo!=null){
			try {
				Date createDate = GlobalConstant.SDF.parse(vInfo.getCreateDate());
				long diff  = new Date().getTime() - createDate.getTime();
				long hour = diff/(1000*60*60);
				//判断时间是否过期
				if(hour<48){
					//判断验证码或邮箱是否错误
					if(vi.getEmail().equals(MD5Util.md5(vInfo.getEmail()))&&vi.getValidateCode().equals(MD5Util.md5(vInfo.getValidateCode()))){
						state = 3;
						//更新前，先查询
						BaseInfo bi = bbdi.get("from BaseInfo b where b.id = '"+Long.parseLong(vi.getBid())+"'");
						//如果存在则进行更新
						if(bi!=null){
							//更改状态
							bi.setState("0");
							//更改修改时间
							bi.setModifyDate(new Date());
							bbdi.saveOrUpdate(bi);
						}else state = 0;
						//验证成功后，删除记录，防止重复验证
						vbdi.delete(vInfo);
					}else state = 2;//验证码或邮箱错误
				}else state = 1;//验证超时，链接失效
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else state = 0;//表示链接失效
		return state;
	}

}
